package com.mgg.auth.authentication.mobile;

import com.mgg.auth.enums.AuthResultEnum;
import com.mgg.auth.exception.AuthenticationCheckException;
import com.mgg.auth.token.MobileAuthenticationToken;
import org.springframework.security.authentication.AuthenticationProvider;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UsernameNotFoundException;


/**
 * @Author lijun
 * @Date: 2018-09-04 12:00:00
 */
public class MobileAuthenticationProvider implements AuthenticationProvider {

	private MobileUserDetailService userDetailsService;

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.springframework.security.authentication.AuthenticationProvider#
	 * authenticate(org.springframework.security.core.Authentication)
	 */
	@Override
	public Authentication authenticate(Authentication authentication) throws AuthenticationException {
		MobileAuthenticationToken authenticationToken = (MobileAuthenticationToken) authentication;
		String phone = (String) authenticationToken.getPrincipal();
		UserDetails user;
		try {
			user = userDetailsService.loadUserByUsername(phone);
		} catch (UsernameNotFoundException e) {
			throw new AuthenticationCheckException(AuthResultEnum.USER_LOAD_ERROR.getCode(),AuthResultEnum.USER_LOAD_ERROR.getMessage());
		}
		if (user == null) {
			throw new AuthenticationCheckException(AuthResultEnum.USER_NOT_SINGUP.getCode(),AuthResultEnum.USER_NOT_SINGUP.getMessage());
		}
		MobileAuthenticationToken authenticationResult = new MobileAuthenticationToken(user, user.getAuthorities());
		authenticationResult.setDetails(authenticationToken.getDetails());
		return authenticationResult;
	}

	/*
	 * (non-Javadoc)
	 * 
	 * @see org.springframework.security.authentication.AuthenticationProvider#
	 * supports(java.lang.Class)
	 */
	@Override
	public boolean supports(Class<?> authentication) {
		return MobileAuthenticationToken.class.isAssignableFrom(authentication);
	}

	public MobileUserDetailService getUserDetailsService() {
		return userDetailsService;
	}

	public void setUserDetailsService(MobileUserDetailService userDetailsService) {
		this.userDetailsService = userDetailsService;
	}
}
